//
//  KKNetworkTools.swift
//  03-Swift网络框架封装
//
//  Created by King.Kong. on 16/5/24.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit

import AFNetworking

enum KKRequestMethod:String {
    case GET = "GET"
    case POST = "POST"
}

struct API {
//    线上
//    static let hostName = "https://dv.api.weibo.com/"
    //线下
    static let hostName = "https://api.weibo.com/"
    static let loadAccessToken = "/oauth2/access_token"
    static let loadUserInfo = "2/users/show.json"
    
    // 首页
    static let loadHomeData = "2/statuses/home_timeline.json"
    
    //发布微博
    static let sendStatus = "2/statuses/update.json"

    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
    
}

class KKNetworkTools: AFHTTPSessionManager {

    
    // 单例对象
//    static let sharedTools:KKNetworkTools = KKNetworkTools()
    static let sharedTools:KKNetworkTools = {
        
        let tools = KKNetworkTools(baseURL: NSURL(string:API.hostName))
        
       tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    
    func request(method: KKRequestMethod, urlString: String, parameters: AnyObject?, finished:(responseObject: AnyObject?, error: NSError?) -> ()) {
        
        let success = { (task:NSURLSessionDataTask, result:AnyObject?) -> () in
            finished(responseObject: result, error: nil)
        }
        
        let failure = { (task:NSURLSessionDataTask?, error:NSError) -> () in
             finished(responseObject: nil, error: error)
        }
        
        if method == KKRequestMethod.GET {
            //调用GET请求
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            //调用POST请求
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)

        }
        
    }
    
}

///MARK: 将用户认证 获取用户信息相关的方法归到这个分类里面
extension KKNetworkTools {
    
    // 请求用户的token
    func loadAccessToken(code:String,finished:((responseObject: AnyObject?,error:NSError?) -> ())) {
        
        let parameters = ["client_id" : client_id,"client_secret" : client_secret,"grant_type" : "authorization_code","code" : code,"redirect_uri" : redirect_uri]
        
        KKNetworkTools.sharedTools.request(.POST, urlString: API.loadAccessToken, parameters: parameters, finished: finished)
    }
    
    // 加载用户信息
    func loadUserInfo(response:[String :AnyObject],finished:((responseObject: AnyObject?,error:NSError?) -> ())) {
        
        let token = response["access_token"]!
        let uid = response["uid"]!
        
        let parameters = ["access_token" : token,"uid" : uid]
        
        KKNetworkTools.sharedTools.request(.GET, urlString: API.loadUserInfo, parameters: parameters, finished: finished)
        
    }
    
}


// MARK:加载首页数据
extension KKNetworkTools {
    
    func loadHomePageData(since_id: Int64,max_id: Int64, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = KKUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        var parameters = ["access_token": token,"count":"10"]
        if since_id > 0 {
            //添加since_id 到参数中
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            //会有bug 会返回max_id 对应的微博
            parameters["max_id"] = "\(max_id - 1)"

        }

        KKNetworkTools.sharedTools.request(.GET, urlString: API.loadHomeData, parameters: parameters, finished: finished)

    }
    
}

/// 发布微博
extension KKNetworkTools {
    func sendStatus(status: String,images:[UIImage],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = KKUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
        
        if images.count > 0 {
            //图片微博  图片上传  AFN已经封装好AFN上传方法 使用POST方法
            let imageData = UIImagePNGRepresentation(images.first!)!
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                //将上传的二进制数据添加到formdata中
                /*
                 1.data          需要上传的二进制数据
                 2.name          服务器接收的字段
                 3.fileName      服务器存储的上传文件的名称  但是这个地方可以随便去  新浪微博服务器会自己根据自己的规则命名
                 4.mimeType      上传的文件的类型  application/octet-stream 忽略文件类型
                 */
                //将多图拼接到formdata中
                for image in images {
                    let imageData = UIImagePNGRepresentation(image)!
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "ococooc", mimeType: "application/octet-stream")
                }
                }, progress: nil, success: { (_, result) in
                    finished(responseObject: result, error: nil)
                }, failure: { (_, error) in
                    finished(responseObject: nil, error: error)
            })
            
            
        } else {
            //文本微博
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        }

    }
}

